package com.atguigu.tingshu.search.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.LongTermsBucket;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggestOption;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import co.elastic.clients.json.JsonData;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.query.search.AlbumIndexQuery;
import com.atguigu.tingshu.search.repository.AlbumInfoIndexRepository;
import com.atguigu.tingshu.search.repository.SuggestIndexRepository;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.search.AlbumInfoIndexVo;
import com.atguigu.tingshu.vo.search.AlbumSearchResponseVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.validation.constraints.Max;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Service
@SuppressWarnings({"all"})
public class SearchServiceImpl implements SearchService {
    @Autowired
    AlbumInfoIndexRepository albumInfoIndexRepository;
    @Autowired
    private AlbumFeignClient albumFeignClient;
    @Qualifier("threadPoolTaskExecutor")
    @Autowired
    private Executor threadPoolTaskExecutor;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private SuggestIndexRepository suggestIndexRepository;
    @Autowired
    private ElasticsearchClient elasticsearchClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 将指定专辑上架到索引库
     *
     * @param albumId 专辑ID
     * @return
     */
    @Override
    public void upperAlbum(Long albumId) {
        //1.创建专辑索引对象
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();

        //2.远程调用专辑服务查询专辑信息，封装专辑以及专辑标签列表
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "专辑{}不存在", albumId);
            //2.1 封装专辑信息
            BeanUtil.copyProperties(albumInfo, albumInfoIndex);

            //2.2 封装专辑标签列表
            List<AlbumAttributeValue> albumAttributeValueVoList = albumInfo.getAlbumAttributeValueVoList();
            if (CollUtil.isNotEmpty(albumAttributeValueVoList)) {
                List<AttributeValueIndex> attributeValueIndexList = albumAttributeValueVoList
                        .stream()
                        .map(a -> BeanUtil.copyProperties(a, AttributeValueIndex.class))
                        .collect(Collectors.toList());
                albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);
            }
            return albumInfo;
        }, threadPoolTaskExecutor);

        //3.远程调用专辑服务查询分类信息，封装1,2级分类ID
        CompletableFuture<Void> BaseCategoryViewCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            BaseCategoryView baseCategoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData();
            Assert.notNull(baseCategoryView, "分类{}不存在", albumInfo.getCategory3Id());
            albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
            albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
        }, threadPoolTaskExecutor);

        //4.远程调用用户服务查询用户信息，封装主播名称
        CompletableFuture<Void> userInfoCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData();
            Assert.notNull(userInfoVo, "用户{}不存在", albumInfo.getUserId());
            albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());
        }, threadPoolTaskExecutor);

        //5.暂时随机为当前专辑生成四项统计数值，基于四项统计数值计算得出热度
        CompletableFuture<Void> statCompletableFuture = CompletableFuture.runAsync(() -> {
            int num1 = RandomUtil.randomInt(2000, 3000);
            int num2 = RandomUtil.randomInt(1000, 2000);
            int num3 = RandomUtil.randomInt(500, 1000);
            int num4 = RandomUtil.randomInt(200, 500);
            albumInfoIndex.setPlayStatNum(num1);
            albumInfoIndex.setSubscribeStatNum(num2);
            albumInfoIndex.setBuyStatNum(num3);
            albumInfoIndex.setCommentStatNum(num4);
            //基于四项统计数值计算得出热度 规则：播放量*0.1 + 订阅量*0.2 + 购买量*0.3 + 评论量*0.4
            BigDecimal hotScore = new BigDecimal(num1).multiply(new BigDecimal("0.1"))
                    .add(new BigDecimal(num2).multiply(new BigDecimal("0.2")))
                    .add(new BigDecimal(num3).multiply(new BigDecimal("0.3")))
                    .add(new BigDecimal(num4).multiply(new BigDecimal("0.4")));
            albumInfoIndex.setHotScore(hotScore.doubleValue());
        }, threadPoolTaskExecutor);

        //6.等待所有任务执行完成
        CompletableFuture.allOf(
                        albumInfoCompletableFuture,
                        BaseCategoryViewCompletableFuture,
                        userInfoCompletableFuture,
                        statCompletableFuture
                ).orTimeout(1, TimeUnit.SECONDS)
                .join();

        //7.保存专辑到索引库
        albumInfoIndexRepository.save(albumInfoIndex);
        //8.将专辑标题存入提词索引库
        this.saveSuggestIndex(albumInfoIndex);
        //9.将专辑ID存入布隆过滤器
        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        if(bloomFilter.isExists()){
            bloomFilter.add(albumId);
        }

    }


    /**
     * 将指定专辑下架，从索引库删除文档
     *
     * @param albumId
     * @return
     */
    //下架
    @Override
    public void lowerAlbum(Long albumId) {
        albumInfoIndexRepository.deleteById(albumId);
    }


    /**
     * 站内搜索
     *
     * @param albumIndexQuery
     * @return
     */
    @Override
    public AlbumSearchResponseVo search(AlbumIndexQuery albumIndexQuery) {
        try {
            //一、构建检索请求对象
            SearchRequest searchRequest = this.buildDSL(albumIndexQuery);
            System.err.println("本次检索DSL,复制到Kibana验证：");
            System.err.println(searchRequest.toString());

            //二、执行检索

            SearchResponse<AlbumInfoIndex> searchResponse = elasticsearchClient.search(searchRequest, AlbumInfoIndex.class);

            //三、解析结果返回
            return this.parseResult(searchResponse, albumIndexQuery);
        } catch (IOException e) {
            log.error("执行检索失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }


    private static final String INDEX_NAME = "albuminfo";

    @Override
    public SearchRequest buildDSL(AlbumIndexQuery albumIndexQuery) {
        //1.创建检索对象构建器对象
        SearchRequest.Builder builder = new SearchRequest.Builder();
        //2.设置索引库名称
        builder.index(INDEX_NAME);

        //3.逐项封装请求体参数
        //3.1 设置请求体参数"query"查询条件
        //3.1.1 创建bool查询组合三大查询条件
        BoolQuery.Builder allConditionBoolQueryBuilder = new BoolQuery.Builder();
        //3.1.2 处理关键字查询条件
        String keyword = albumIndexQuery.getKeyword();
        if (StringUtils.isNotBlank(keyword)) {
            allConditionBoolQueryBuilder.must(m -> m.match(m1 -> m1.field("albumTitle").query(keyword)));
        }

        //3.1.3 处理1,2,3级分类过滤条件
        Long category1Id = albumIndexQuery.getCategory1Id();
        if (category1Id != null) {
            allConditionBoolQueryBuilder.filter(f -> f.term(t -> t.field("category1Id").value(category1Id)));
        }
        Long category2Id = albumIndexQuery.getCategory2Id();
        if (category2Id != null) {
            allConditionBoolQueryBuilder.filter(f -> f.term(t -> t.field("category2Id").value(category2Id)));
        }
        Long category3Id = albumIndexQuery.getCategory3Id();
        if (category3Id != null) {
            allConditionBoolQueryBuilder.filter(f -> f.term(t -> t.field("category3Id").value(category3Id)));
        }

        //3.1.4 处理多组标签过滤条件 标签id:标签值id
        List<String> attributeList = albumIndexQuery.getAttributeList();
        if (CollUtil.isNotEmpty(attributeList)) {
            for (String attribute : attributeList) {
                //每循环一次封装一个filter对应的Nested查询对象
                String[] split = attribute.split(":");
                if (split != null && split.length == 2) {
                    allConditionBoolQueryBuilder.filter(f -> f.nested(
                            n -> n.path("attributeValueIndexList")
                                    .query(q -> q.bool(b -> b.must(m -> m.term(t -> t.field("attributeValueIndexList.attributeId").value(split[0])))
                                            .must(m -> m.term(t -> t.field("attributeValueIndexList.valueId").value(split[1])))))
                    ));
                }
            }
        }

        builder.query(allConditionBoolQueryBuilder.build()._toQuery());
        //3.2 设置请求体参数"from","size"分页
        Integer pageNo = albumIndexQuery.getPageNo();
        Integer pageSize = albumIndexQuery.getPageSize();
        int from = (pageNo - 1) * pageSize;
        builder.from(from).size(pageSize);
        //3.3 设置请求体参数"highlight"高亮
        if (org.apache.commons.lang3.StringUtils.isNotBlank(keyword)) {
            builder.highlight(h -> h.fields("albumTitle", h1 -> h1.preTags("<font style='color:red'>").postTags("</font>")));
        }
        //3.4 设置请求体参数"sort"排序  形式：高亮字段（1,2,3）：排序规则
        String order = albumIndexQuery.getOrder();
        if (StringUtils.isNotBlank(order)) {
            String[] split = order.split(":");
            if (split != null && split.length == 2) {
                //确定排序字段 以及 排序方向
                String orderField = "";
                switch (split[0]) {
                    case "1":
                        orderField = "hotScore";
                        break;
                    case "2":
                        orderField = "playStatNum";
                        break;
                    case "3":
                        orderField = "createTime";
                        break;
                }
                SortOrder sortOrder = split[1].equals("asc") ? SortOrder.Asc : SortOrder.Desc;
                String finalOrderField = orderField;
                builder.sort(s -> s.field(f -> f.field(finalOrderField).order(sortOrder)));
            }
        }
        //3.5 设置请求体参数"_source"指定字段响应
        builder.source(s -> s.filter(f -> f.excludes("attributeValueIndexList",
                "hotScore",
                "commentStatNum",
                "buyStatNum",
                "subscribeStatNum",
                "announcerName")));

        //4.基于检索对象构建器对象返回实际检索请求对象
        return builder.build();
    }

    @Override
    public AlbumSearchResponseVo parseResult(SearchResponse<AlbumInfoIndex> searchResponse, AlbumIndexQuery albumIndexQuery) {
        //1.创建响应VO对象
        AlbumSearchResponseVo vo = new AlbumSearchResponseVo();
        //2.封装VO中分页相关四项属性
        //2.1 从入参直接获取页码跟页大小
        Integer pageNo = albumIndexQuery.getPageNo();
        Integer pageSize = albumIndexQuery.getPageSize();
        //2.2 从ES响应结果获取总记录数
        long total = searchResponse.hits().total().value();
        //2.3 计算总页数
        long totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        vo.setPageNo(pageNo);
        vo.setPageSize(pageSize);
        vo.setTotal(total);
        vo.setTotalPages(totalPages);

        //3.封装VO中检索到专辑列表集合属性
        List<Hit<AlbumInfoIndex>> hits = searchResponse.hits().hits();
        if (CollUtil.isNotEmpty(hits)) {
            //采用Stream流将检索到文档类型从AlbumInfoIndex转为AlbumInfoIndexVo
            List<AlbumInfoIndexVo> list = hits.stream().map(hit -> {
                AlbumInfoIndex albumInfoIndex = hit.source();
                //处理高亮字段
                Map<String, List<String>> stringListMap = hit.highlight();
                if (CollUtil.isNotEmpty(stringListMap)) {
                    String hightLightText = stringListMap.get("albumTitle").get(0);
                    albumInfoIndex.setAlbumTitle(hightLightText);
                }
                return BeanUtil.copyProperties(albumInfoIndex, AlbumInfoIndexVo.class);
            }).collect(Collectors.toList());
            vo.setList(list);
        }
        //4.响应VO对象
        return vo;
    }


    /**
     * 查询1级分类下置顶3级分类热度TOP6专辑
     *
     * @param category1Id
     * @return [{"baseCategory3":{三级分类对象},list:[专辑列表]},,{其他6个置顶分类热门专辑Map}]
     */
    @Override
    public List<Map<String, Object>> channel(Long category1Id) {
        try {
            //1.根据1级分类ID获取置顶三级分类ID
            //1.1 远程调用---远程调用专辑微服务获取置顶3级分类
            List<BaseCategory3> baseCategory3List = albumFeignClient.findTopBaseCategory3(category1Id).getData();
            Assert.notNull(baseCategory3List, "一级分类{}置顶三级分类不存在", category1Id);

            //1.2 获取置顶三级分类ID列表
            List<FieldValue> fieldValueList = baseCategory3List
                    .stream()
                    .map(c3 -> FieldValue.of(c3.getId()))
                    .collect(Collectors.toList());

            //1.3 为了封装结果Map中分类对象，将三级分类List转为Map<3级分类ID，3级分类对象>
            Map<Long, BaseCategory3> category3Map = baseCategory3List
                    .stream()
                    .collect(Collectors.toMap(BaseCategory3::getId, baseCategory3 -> baseCategory3));

            //2. 调用ES进行检索：置顶分类热门专辑
            SearchResponse<AlbumInfoIndex> searchResponse = elasticsearchClient.search(
                    s -> s.index(INDEX_NAME)
                            .size(0)
                            .query(q -> q.terms(t -> t.field("category3Id").terms(t1 -> t1.value(fieldValueList))))
                            .aggregations(
                                    "c3_agg", a -> a.terms(t -> t.field("category3Id").size(7))
                                            .aggregations("top6", a1 -> a1.topHits(
                                                    t -> t.size(6)
                                                            .sort(s1 -> s1.field(f -> f.field("hotScore").order(SortOrder.Desc)))
                                                            .source(s1 -> s1.filter(f -> f.excludes("attributeValueIndexList",
                                                                    "hotScore",
                                                                    "commentStatNum",
                                                                    "buyStatNum",
                                                                    "subscribeStatNum",
                                                                    "announcerName")))
                                            ))
                            )
                    , AlbumInfoIndex.class);

            //3.解析聚合结果，获取置顶分类包含热度TOP6专辑列表 将7个置顶分类热门专辑Map封装到List集合中
            List<LongTermsBucket> longTermsBuckets = searchResponse.aggregations().get("c3_agg").lterms().buckets().array();
            //3.1 遍历三级分类聚合结果，每遍历一次就封装一个置顶分类热门专辑Map对象
            if (CollUtil.isNotEmpty(longTermsBuckets)) {
                List<Map<String, Object>> topCategory3MapList = longTermsBuckets
                        .stream()
                        .map(bucket -> {
                            //3.1.1 创建Map封装置顶分类热门专辑
                            Map<String, Object> map = new HashMap<>();
                            //3.1.2 获取聚合结果中三级分类ID //封装3级分类对象
                            long topCategory3Id = bucket.key();
                            map.put("category3Id", topCategory3Id);
                            //3.1.3 获取top6专辑列表
                            //获取三级分类聚合内子聚合"top6"
                            List<Hit<JsonData>> top6HitsList = bucket.aggregations().get("top6")
                                    .topHits().hits().hits();
                            if (CollUtil.isNotEmpty(top6HitsList)) {
                                //遍历Hit集合 将集合泛型从Hit转为AlbumInfoIndex类型
                                List<AlbumInfoIndex> topAlbumList = top6HitsList.stream()
                                        .map(hit -> {
                                            //获取专辑JSON字符串
                                            String albumInfoIndexJSONStr = hit.source().toString();
                                            //将专辑JSON字符串转为AlbumInfoIndex对象
                                            AlbumInfoIndex albumInfoIndex =
                                                    JSON.parseObject(albumInfoIndexJSONStr,
                                                            AlbumInfoIndex.class);
                                            return albumInfoIndex;
                                        }).collect(Collectors.toList());
                                //3.2 封装置顶分类热门专辑Map
                                map.put("baseCategory3", category3Map.get(topCategory3Id));
                                map.put("list", topAlbumList);
                            }
                            return map;
                        }).collect(Collectors.toList());
                return topCategory3MapList;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


    @Override
    public void saveSuggestIndex(AlbumInfoIndex albumInfoIndex) {
        //构建索引库文档对象
        SuggestIndex suggestIndex = new SuggestIndex();

        suggestIndex.setId(albumInfoIndex.getId().toString());

        String albumTitle = albumInfoIndex.getAlbumTitle();
        suggestIndex.setTitle(albumTitle);

        suggestIndex.setKeyword(new Completion(new String[]{albumTitle}));

        //1.1 将汉字转为汉语拼音 jing dian liu sheng ji
        String albumTitlePinyin = PinyinUtil.getPinyin(albumTitle, "");// 输出: jingdianliushengji
        // 设置 keywordPinyin 字段的值
        suggestIndex.setKeywordPinyin(new Completion(new String[]{albumTitlePinyin}));
        //汉字  转拼音首字母
        String albumTitleFirstLetter = PinyinUtil.getFirstLetter(albumTitle, "");// 输出: jdlsj
        // 设置 keywordSequence 字段的值
        suggestIndex.setKeywordSequence(new Completion(new String[]{albumTitleFirstLetter}));

        //2.存入提词文档记录到提词索引库
        suggestIndexRepository.save(suggestIndex);

    }


    private static final String SUGGEST_INDEX = "suggestinfo";

    /**
     * 根据用户已录入字符查询提词索引库进行自动补全关键字
     *
     * @param keyword
     * @return
     */
    @Override
    public List<String> completeSuggest(String keyword) {
        try {
            //1.发起自动补全请求
            SearchResponse<SuggestIndex> searchResponse = elasticsearchClient.search(s ->
                            s.index(SUGGEST_INDEX)
                                    .suggest(
                                            s1 -> s1.suggesters("letter-suggest", fs -> fs.prefix(keyword).completion(c -> c.field("keywordSequence").size(10).skipDuplicates(true)))
                                                    .suggesters("pinyin-suggest", s2 -> s2.prefix(keyword).completion(c -> c.field("keywordPinyin").size(10).skipDuplicates(true)))
                                                    .suggesters("keyword-suggest", s2 -> s2.prefix(keyword).completion(c -> c.field("keyword").size(10).skipDuplicates(true)))
                                    )
                    , SuggestIndex.class);
            //2.解析ES自动补全结果
            Set<String> hashSet = new HashSet<>();
            //2.1 解析建议结果-通过不同建议参数名获取汉字、拼音等提示词结果
            //解析方法
            hashSet.addAll(this.parseSuggestResult(searchResponse, "letter-suggest"));
            hashSet.addAll(this.parseSuggestResult(searchResponse, "pinyin-suggest"));
            hashSet.addAll(this.parseSuggestResult(searchResponse, "keyword-suggest"));
            //如果提示词数量小于10个，就补全至10个
            if (hashSet.size() < 10) {
                SearchResponse<AlbumInfoIndex> matchSearchResponse = elasticsearchClient.search(
                        s -> s.index(INDEX_NAME)
                                .query(q -> q.match(m -> m.field("albumTitle").query(keyword)))
                                .size(10)
                        , AlbumInfoIndex.class
                );
                //获取搜索结果里的元数据信息
                HitsMetadata<AlbumInfoIndex> hits = matchSearchResponse.hits();
                //从元数据里提取出具体的搜索匹配项列表。
                List<Hit<AlbumInfoIndex>> hitList = hits.hits();
                if (CollectionUtil.isNotEmpty(hitList)) {
                    for (Hit<AlbumInfoIndex> hit : hitList) {
                        AlbumInfoIndex source = hit.source();
                        //2.2.2 将检索到专辑标题内容加入到提词结果列表中
                        hashSet.add(source.getAlbumTitle());
                        if (hashSet.size() >= 10) {
                            break;
                        }
                    }
                }
            }
            if (hashSet.size() > 10) {
                //取前十个
                return new ArrayList<>(hashSet).subList(0, 10);
            } else {
                return new ArrayList<>(hashSet);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 解析建议词结果
     *
     * @param searchResponse ES检索结果对象
     * @param suggestName    自定义建议词参数名称
     * @return
     */
    @Override
    public Collection<String> parseSuggestResult(SearchResponse<SuggestIndex> searchResponse, String suggestName) {
        //根据自定义建议词参数名称获取结果列表
        List<String> list = new ArrayList<>();
        List<Suggestion<SuggestIndex>> suggestionList = searchResponse.suggest().get(suggestName);
        if (CollUtil.isNotEmpty(suggestionList)) {
            //遍历得到建议对象
            for (Suggestion<SuggestIndex> suggestIndexSuggestion : suggestionList) {
                for (CompletionSuggestOption<SuggestIndex> option : suggestIndexSuggestion.completion().options()) {
                    SuggestIndex suggestIndex = option.source();
                    list.add(suggestIndex.getTitle());
                }
            }
        }
        return list;
    }


    /**
     * 更新Redis小时榜
     *
     * @return
     */
    @Override
    public void updateLatelyAlbumRanking() {
        try {
        /*干什么：更新排行榜、
        怎么做：获得排行榜

        * */
            //1.1 远程调用专辑服务获取一级分类ID列表
            List<BaseCategory1> baseCategory1List = albumFeignClient.findAllCategory1().getData();
            Assert.notNull(baseCategory1List, "一级分类列表为空！");
            //1IdList
            List<Long> category1IdList = baseCategory1List
                    .stream()
                    .map(BaseCategory1::getId)
                    .collect(Collectors.toList());
            //2.遍历一级分类id列表
            for (Long category1Id : category1IdList) {
                //定义Redis中小时榜hash的Key：前缀+id
                String redisKey = RedisConstant.RANKING_KEY_PREFIX + category1Id;
                //创建绑定hash对象方便操作hash结构
                BoundHashOperations<String, String, List<AlbumInfoIndex>> hashOps = redisTemplate.boundHashOps(redisKey);
                //5个排序字段
                String[] rankingDimensionArray
                        = new String[]{
                        "hotScore",
                        "playStatNum",
                        "subscribeStatNum",
                        "buyStatNum",
                        "commentStatNum"};
                for (String rankingDimension : rankingDimensionArray) {
                    SearchResponse<AlbumInfoIndex> searchResponse = elasticsearchClient.search(
                            s -> s.index(INDEX_NAME).size(20)
                                    .query(q -> q.term(t -> t.field("category1Id").value(category1Id)))
                                    .sort(s1 -> s1.field(f -> f.field(rankingDimension).order(SortOrder.Desc)))
                            , AlbumInfoIndex.class);

                    //2.解析ES检索结果，将专辑列表保存到Redis中Hash中
                    List<Hit<AlbumInfoIndex>> hitList = searchResponse.hits().hits();
                    if (CollUtil.isNotEmpty(hitList)) {
                        List<AlbumInfoIndex> top20List = hitList.stream().map(hit -> {
                            AlbumInfoIndex source = hit.source();
                            return source;
                        }).collect(Collectors.toList());
                        hashOps.put(rankingDimension, top20List);
                    }
                }
            }

        } catch (IOException e) {
            log.error("更新Redis小时榜失败！");
            throw new RuntimeException(e);
        }
    }


    /**
     * 查询Redis中不同分类下不同维度TOP20专辑列表
     *
     * @param category1Id
     * @param dimension
     * @return
     */
    @Override
    public List<AlbumInfoIndexVo> findRankingList(Long category1Id, String dimension) {
        /*
        * 目的：查询一级分类下的前20专辑
        * 条件：一级分类id
        * 怎么做：
        * */
        //定义Redis中小时榜hash的Key
        String redisKey = RedisConstant.RANKING_KEY_PREFIX + category1Id;
        String field = dimension;
        //创建绑定hash对象方便操作hash结构
        BoundHashOperations<String,String,List<AlbumInfoIndex>> hashOps =
                redisTemplate.boundHashOps(redisKey);
        boolean flag = hashOps.hasKey(field);
        if (flag){
            //获取hash结构中的字段数据
            List<AlbumInfoIndex> list = hashOps.get(field);
            //在遍历字段获得专辑list
            List<AlbumInfoIndexVo> collect = list
                    .stream()
                    .map(albumInfoIndex -> BeanUtil.copyProperties(albumInfoIndex, AlbumInfoIndexVo.class))
                    .collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
